package library.and.xps.com.step.view.activity;

import android.content.Intent;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.jude.utils.JUtils;
import com.lvfq.pickerview.TimePickerView;
import com.squareup.okhttp.Request;
import com.zhy.autolayout.AutoRelativeLayout;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import library.and.xps.com.step.EventBusCommond;
import library.and.xps.com.step.R;
import library.and.xps.com.step.URLConstants;
import library.and.xps.com.step.m.model.CreateChallenge;
import library.and.xps.com.step.m.model.MemberInDepartment;
import library.and.xps.com.step.m.model.RequestParams;
import library.and.xps.com.step.m.netapi.OkHttpClientUtils;
import library.and.xps.com.step.net.ResponceWrapper;
import library.and.xps.com.step.util.HttpResponsHelper;
import library.and.xps.com.step.util.PikerUtils;
import library.and.xps.com.step.util.RequestCallback;
import library.and.xps.com.step.util.TeamHelper;
import library.and.xps.com.step.view.base.BaseActivity;

public class CreateChallengeActivity extends BaseActivity {
    TextView actionbar_tv_right, tv_c_starttime, tv_c_endtime, tv_chips, tv_challengto;
    ImageView iv_back;
    AutoRelativeLayout al_Tochallenger, al_chips, al_starttime, al_endtime;
    String paramStartTimeStr;
    String paramEndTimeStr;
    Date startDate;
    Date endDate;
    String chipStr = "真心话大冒险";
    int memberIdTochallengeTo = 0;
    private static final int request_code_ChooseMember = 1;
    String[] templates = {"真心话大冒险", "吃货大礼包", "一周爱心早餐"};

    @Override
    protected int getLayout() {
        return R.layout.activity_create_challenge;
    }

    @Override
    protected void setData() {
        initActiveTime();
    }

    @Override
    protected void init() {
        tv_chips = r2v(R.id.tv_chips);
        tv_c_starttime = r2v(R.id.tv_c_starttime);
        tv_c_endtime = r2v(R.id.tv_c_endtime);
        iv_back = r2v(R.id.actionbar_iv_back);

        iv_back.setOnClickListener(this);
        al_Tochallenger = r2v(R.id.al_Tochallenger);
        al_Tochallenger.setOnClickListener(this);
        al_chips = r2v(R.id.al_chips);
        al_chips.setOnClickListener(this);
        al_starttime = r2v(R.id.al_starttime);
        al_starttime.setOnClickListener(this);
        al_endtime = r2v(R.id.al_endtime);
        tv_challengto = r2v(R.id.tv_challengto);
        al_endtime.setOnClickListener(this);
        actionbar_tv_right = r2v(R.id.actionbar_tv_right);
        actionbar_tv_right.setVisibility(View.VISIBLE);
        actionbar_tv_right.setOnClickListener(this);
        ((TextView) r2v(R.id.actionbar_tv_title)).setText("创建挑战");
        actionbar_tv_right.setText("创建");

    }

    boolean ableCreate() {
        if (tv_challengto.getText().toString().equals("选择")) {
            Snackbar.make(tv_challengto, "请选择PK对象", Snackbar.LENGTH_LONG)
                    .setAction("确定", null).show();
            return false;
        }
        return true;
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.actionbar_tv_right:

                if (ableCreate()) {
                    createChallenge();
                }

                break;
            case R.id.al_Tochallenger:
                Intent iChooseMember = new Intent(this, ChooseMemberChallengerToActivity.class);
                startActivityForResult(iChooseMember, request_code_ChooseMember);
                break;
            case R.id.al_chips:
                Intent i = new Intent(this, ChallengerChipsChooseActivity.class);
                startActivityForResult(i, 0);
                break;
            case R.id.al_starttime:
                startTimerPicker();
                break;
            case R.id.al_endtime:
                endTimerPicker();
                break;
            case R.id.actionbar_iv_back:
                finish();
                break;
        }
    }

    void initActiveTime() {
        startDate = new Date();
        endDate = new Date();
        SimpleDateFormat tv_format = new SimpleDateFormat("MM月dd日 HH:mm");//格式化成显示需要的格式

        Calendar startTimeCalender = Calendar.getInstance();
        startTimeCalender.setTime(startDate);
        startTimeCalender.set(Calendar.HOUR_OF_DAY, 0);//设置从0点0分开始
        startTimeCalender.set(Calendar.MINUTE, 0);
        startDate.setTime(startTimeCalender.getTime().getTime());

        Calendar endTimeCalender = Calendar.getInstance();//设置结束时间到次日的23:59
        endTimeCalender.setTime(startDate);
        endTimeCalender.add(Calendar.DAY_OF_MONTH, 2);
        endDate.setTime(endTimeCalender.getTime().getTime() - 60000);

        tv_c_starttime.setText(tv_format.format(startDate));
        tv_c_endtime.setText(tv_format.format(endDate));

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");//格式化成服务器需要的格式
        paramStartTimeStr = simpleDateFormat.format(startDate);

        SimpleDateFormat paramEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        paramEndTimeStr = paramEndTime.format(endDate);

    }

    void startTimerPicker() {
        PikerUtils.alertTimerPicker(this, TimePickerView.Type.YEAR_MONTH_DAY, "yyyy-MM-dd HH:mm", new PikerUtils.TimerPickerCallBack() {
            @Override
            public void onTimeSelect(Date date) {
                if (date.after(endDate)) {
                    JUtils.Toast("开始时间不能晚于结束时间");
                    return;
                }
                startDate = date;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                paramStartTimeStr = simpleDateFormat.format(date);
                SimpleDateFormat tv_format = new SimpleDateFormat("MM月dd日 HH:mm");
                tv_c_starttime.setText(tv_format.format(date));
            }
        });
    }

    void endTimerPicker() {
        PikerUtils.alertTimerPicker(this, TimePickerView.Type.YEAR_MONTH_DAY, "yyyy-MM-dd HH:mm", new PikerUtils.TimerPickerCallBack() {
            @Override
            public void onTimeSelect(Date date) {
                if (date.before(startDate)) {
                    JUtils.Toast("结束时间不能早于开始时间");
                    return;
                }
                endDate = date;
                date.setTime(date.getTime() + 86340000);
                SimpleDateFormat paramEndTime = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                paramEndTimeStr = paramEndTime.format(date);
                SimpleDateFormat tv_format = new SimpleDateFormat("MM月dd日 HH:mm");
                tv_c_endtime.setText(tv_format.format(date));
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data != null) {
            if (resultCode == 1) {//筹码选择
                chipStr = data.getStringExtra("chip");
                tv_chips.setText(chipStr);
            } else if (resultCode == 2) {//pk对象选择
                MemberInDepartment.ListBean member = (MemberInDepartment.ListBean) data.getSerializableExtra("member");
                memberIdTochallengeTo = member.getUserid();
                tv_challengto.setText(member.getNickname());
            }
        }
    }

    void createChallenge() {
        if (getUser() == null || !TeamHelper.getIns().hasTeam()) return;

        String json = "";
        if (containsTemplate(chipStr)) {
            json = RequestParams.getNewInstance().setTeamid(TeamHelper.getIns().getCurT().getTeamid())
                    .setChallenger(getUser().getUserid())
                    .setBechallenged(memberIdTochallengeTo + "")
                    .setChip(chipStr)
                    .setStarttime(paramStartTimeStr)
                    .setEndtime(paramEndTimeStr).getJson().toString();
        }
         else {
            json = RequestParams.getNewInstance().setTeamid(TeamHelper.getIns().getCurT().getTeamid())
                    .setChallenger(getUser().getUserid())
                    .setBechallenged(memberIdTochallengeTo + "")
                    .setSelfchip(chipStr)
                    .setStarttime(paramStartTimeStr)
                    .setEndtime(paramEndTimeStr).getJson().toString();
        }

        OkHttpClientUtils.postJsonStringAsync(this, URLConstants.PERSONACTIVE.CREATEUSERPK, json, new RequestCallback() {
            @Override
            public void onFailure(Request request, Exception e) {
                e.printStackTrace();
                dissmisDialog();
            }

            @Override
            public void onResponse(ResponceWrapper response) {
                dissmisDialog();
                if (HttpResponsHelper.SuccessResponce(response)) {
                    CreateChallenge createChallenge = new Gson().fromJson(response.getBody(), CreateChallenge.class);
                    if (createChallenge.isStatus()) {
                        JUtils.Toast("已发出挑战!");
                        EventBus.getDefault().post(EventBusCommond.FREASH_TEAM_CHALLENGE);
                        finish();
                    }
                }
            }

            @Override
            public void onStart() {
                showDialog();
            }
        }, "");
    }

    boolean containsTemplate(String content) {
        for(int i=0;i<templates.length;i++)
            if(templates[i].contains(content)) return true;
        return false;
    }



}
